<template>
  <div>
    <!--搜索面板-->
    <div class="search-pad">
      <input type="text" name="" id=""
             v-model="searchText"
             @focus="searchFocus()"
             @blur="searchBlur()"
             @input="search">
      <button v-show="isShowSearchBtn">搜索</button>
      <button v-show="!isShowSearchBtn" @click="showRight()">筛选</button>
    </div>
    <!--物品大类面板-->
    <div class="system-pad">
      <div v-for="belongType in belongTypes" :key="belongType.belongTypeName"
           :class="['system-item',{'system-select':systemIndex==belongType.belongTypeName}]"
           @click="selectSystemProduct(belongType.belongTypeName)">
        <span>{{ belongType.belongTypeName }}</span>
      </div>
    </div>
    <!--物品展示列表-->
    <div class="product-list">
      <ul>
        <li v-for="product in products" :key="product.id">
          <img v-if="product.productPhoto"
               :src="product.productPhoto.productPhotoUrl" alt="">
          <div>
            <p class="p-name">{{ product.productName }}</p>
            <p class="p-type">类别：{{ product.typeName }}</p>
            <p class="p-price" v-if="product.productSale">
              &yen;{{ product.productSale.salePrice }}/张
            </p>
            <p class="p-cart" @click="onAddCart(product.productNo,1)">
              <em></em>
              <i>x1</i>
            </p>
          </div>
        </li>
      </ul>
      <!--左边物品类型面板-->
      <div :class="['left-menu',{'left-menu-show':isShowLeft}]">
        <div class="left-switch" @click="showLeft()">
          <img src="/img/dealerImgs/up.png" alt="">
        </div>
        <ul>
          <li v-for="productType in productTypes"
              :key="productType.id"
              :class="{'left-item-select':typeSelected==productType.typeNo}"
              @click="selectType(productType.typeNo)">
            {{ productType.typeName }}
          </li>
        </ul>
      </div>
    </div>
    <!--右边物品属性面板-->
    <div class="right-pad">
      <div class="list-pad">
        <ul class="f-type-list">
          <template v-for="(values,key) in productProps">
            <li v-if="values.length > 0" :key="key">
              <p>{{ GetPropKey(key, 1) }}</p>
              <ul class="f-item-list">
                <li
                  v-for="value in values"
                  :key="value"
                  @click="selectProp(GetPropKey(key, 0),value)">
                  <span :class="{'prop-select':propSelect[GetPropKey(key, 0)] == value}">{{ value }}</span>
                </li>
              </ul>
              <div class="clear-tag"></div>
            </li>
          </template>
        </ul>
      </div>
      <div class="right-edit">
        <button @click="confirmFilter()"
                style="background-color:rgb(188,0,0); color:#fff">确定
        </button>
        <button @click="hideRight()">取消</button>
      </div>
    </div>
    <div class="cover" v-show="isShowCover" @click="hideRight()"></div>
  </div>
</template>

<script>
import {onMounted, reactive, toRefs} from 'vue'
import {addCart, getBelongType, getProduct, getPror, getType} from '@/HttpRequests/ProductListRequest'
import {useRoute, useRouter} from 'vue-router'

export default {
  setup() {

    let router = useRouter()
    let route = useRoute()
    const pageController = reactive({
      isShowLeft: false,
      isShowCover: false,
      isShowSearchBtn: false
    })
    const productInfo = reactive({
      systemIndex: '板材',
      searchText: '',
      propSelect: {},
      products: [],
      belongTypes: [],
      productTypes: [],
      productProps: {},
      typeSelected: '',
      timer: 0,
      pageIndex: 1,
      /**
       * 获取物品
       */
      getProducts: async (belongTypeName, productType, searchText, productProps) => {
        let products = await getProduct({
          searchText: searchText,
          belongTypeName: belongTypeName,
          productType: productType,
          productProps: productProps,
          sort: 'productName',
          pageIndex: productInfo.pageIndex
        })
        products.forEach(p => {
          productInfo.products.push(p)
        })
      },
      getBelongTypes: async () => {
        productInfo.belongTypes = await getBelongType()
      },
      /**
       * 点击大类时，清空搜索栏
       * 搜索时要考虑大类
       * @param belongTypeName
       * @returns {Promise<void>}
       */
      selectSystemProduct: async (belongTypeName) => {
        productInfo.propSelect = {}
        productInfo.typeSelected = ''
        productInfo.searchText = ''
        await router.push(`/productList?belongType=${belongTypeName}`)
      },
      /**
       * 从后端获取物品类型
       * @param belongTypeName
       * @returns {Promise<void>}
       */
      getTypes: async (belongTypeName) => {
        productInfo.productTypes = await getType(belongTypeName)
      },
      /**
       * 选择物品类型，选择物品类型时可以清空搜索栏
       * @param typeNo
       * @returns {Promise<void>}
       */
      selectType: async (typeNo) => {
        productInfo.propSelect = {}
        productInfo.searchText = ''
        if (productInfo.typeSelected == typeNo) {
          productInfo.typeSelected = ''
        } else {
          productInfo.typeSelected = typeNo
        }
        setRouter()
      },
      /**
       * 从后端获取物品属性
       * @param belongTypeName
       * @param typeNo
       * @returns {Promise<void>}
       */
      getProps: async (belongTypeName, typeNo) => {
        const res = await getPror({
          belongTypeName,
          typeNo
        })
        productInfo.productProps = res
      },
      /**
       * 获取物品属性种类的名称
       * @param key
       * @param index
       * @returns {*}
       */
      GetPropKey: (key, index) => {
        return key.split('|')[index]
      },
      /**
       * 搜索物品
       */
      search: () => {
        clearTimeout(productInfo.timer)
        productInfo.timer = setTimeout(async () => {
          setRouter()
        }, 1000)
      },
      /**
       * 选择属性
       * @param propKey
       * @param propValue
       */
      selectProp: (propKey, propValue) => {
        if (productInfo.propSelect[propKey] == propValue) {
          productInfo.propSelect[propKey] = ''
        } else {
          productInfo.propSelect[propKey] = propValue
        }
      },
      /**
       * 确认筛选
       */
      confirmFilter: () => {
        setRouter()
      },
      onAddCart: async (productNo , productNum) => {
        const customerNo = localStorage['cno']
        await addCart({
          customerNo : customerNo,
          productNo,
          productNum
        })
      }
    })
    /**
     * 将选中的物品属性转化成字符串
     */
    const productPropToString = () => {
      // 选择属性字符串清空
      productProps = ''
      for (const key in productInfo.propSelect) {
        const value = productInfo.propSelect[key]
        if (value != '') {
          productProps += `${key}_${value}^`
        }
      }
      productProps = productProps.substring(0, productProps.length - 1)
    }

    /**
     * 设置路由
     */
    const setRouter = () => {
      // 根地址，包含根路由以及物品大类信息
      let url = `/productList?belongType=${productInfo.systemIndex}`
      // 拼接物品搜索信息
      if (productInfo.searchText != '') {
        url += `&keywords=${productInfo.searchText}`
      }
      // 拼接物品类型
      if (productInfo.typeSelected.trim() != '') {
        url += `&type=${productInfo.typeSelected}`
      }
      // 拼接物品属性
      productPropToString()
      if (productProps != '') {
        url += `&prop=${productProps}`
      }
      router.push(url)
    }

    const showLeft = () => {
      pageController.isShowLeft = !pageController.isShowLeft
    }

    const searchFocus = () => {
      pageController.isShowSearchBtn = true
    }

    const searchBlur = () => {
      pageController.isShowSearchBtn = false
    }

    const showRight = () => {
      pageController.isShowCover = true
      document.querySelector('.right-pad').style.right = '0'
    }

    const hideRight = () => {
      pageController.isShowCover = false
      document.querySelector('.right-pad').style.right = '-85%'
    }

    let keywords = ''
    let systemIndex = ''
    let productType = ''
    let productProps = ''
    /**
     * 解析地址
     */
    const resolutionAddress = () => {
      productInfo.searchText = keywords = route.query.keywords ?? ''
      productInfo.systemIndex = systemIndex = route.query.belongType ?? '板材'
      productInfo.typeSelected = productType = route.query.type ?? ''
      productProps = route.query.prop ?? ''
      // 格式大约如是：&prop=xxx_xxx%5Eyyy_yyy
      if (productProps != '') {
        let arrayProductProps = productProps.split('^')
        for (let i = 0; i < arrayProductProps.length; i++) {
          const element = arrayProductProps[i]
          productInfo.propSelect[element.split('_')[0]] = element.split('_')[1]
        }
      }
    }

    /**
     * 监听页面的滚动事件
     */
    const handleScroll = () => {
      let htmlDom = document.querySelector('html');
      // 1.获取当前整个页面长度
      let htmlHeight = htmlDom.offsetHeight
      // 2.获取滚动条离顶部的距离
      let scrollTop = htmlDom.scrollTop
      // 3.获取屏幕可视区域的长度
      let screenHeight = document.documentElement.clientHeight
      // 4.获取可视区域底部到整个页面底部的距离
      let diffHeight = htmlHeight - scrollTop - screenHeight
      if (diffHeight == 0 && scrollTop > 0){
        onPageChange()
      }
    }

    const onPageChange = async () => {
      productInfo.pageIndex++
      await productInfo.getProducts(systemIndex, productType, keywords, productProps)
    }

    onMounted(async () => {
      window.addEventListener('scroll', handleScroll)
      resolutionAddress()
      await productInfo.getProps(systemIndex, productType)
      await productInfo.getProducts(systemIndex, productType, keywords, productProps)
      await productInfo.getTypes(systemIndex)
      await productInfo.getBelongTypes()
    })

    return {
      ...toRefs(pageController),
      ...toRefs(productInfo),
      showLeft,
      searchFocus,
      searchBlur,
      showRight,
      hideRight
    }
  }
}
</script>

<style lang="scss" scoped>
.i-search:after {
  background-color: #b70101 !important;
}

.search-pad {
  z-index: 10;
  position: fixed;
  width: 100%;
  padding: 6px 20px;
  background-color: #f0f0f0;
  display: flex;

  input {
    height: 28px;
    box-sizing: border-box;
    border: 1px solid #ddd;
    border-radius: 3px;
    flex: 1;
    outline: none;
  }

  button {
    background-color: transparent;
    width: 56px;
    border: 0 none;
    font-size: 14px;
    font-weight: bold;
    color: #333;
    outline: none;
  }
}

.system-pad {
  z-index: 10;
  position: fixed;
  width: 100%;
  top: 40px;
  background-color: #fff;
  display: flex;

  .system-item {
    flex: 1;
    text-align: center;
    border-bottom: 1px #ddd solid;
    border-right: 1px transparent solid;
    border-left: 1px transparent solid;

    span {
      border: 0 none !important;
      background-color: #f0f2f5;
      margin: 6px 5px;
      font-size: 12px;
      font-weight: normal;
      text-align: center;
      border-radius: 4px;
      padding: 6px 0;
      display: block;
      height: 22px;
      line-height: 12px;
    }

  }

  .system-select {
    border-bottom: 1px transparent solid;
    border-right: 1px #ddd solid;
    border-left: 1px #ddd solid;

    span {
      background-color: transparent;
    }
  }
}

.product-list {
  padding-top: 75px;

  ul {
    background-color: #fff;

    li {
      list-style: none;;
      height: 88px;
      padding-left: 108px;
      position: relative;

      img {
        height: 66px;
        width: 66px;
        background-color: #ccc;
        position: absolute;
        left: 28px;
        top: 11px;
      }

      div {
        overflow: hidden;
        padding: 10px 0;
        border-bottom: 1px solid #f0f0f0;
        padding-bottom: 6px;
        text-align: left;

        .p-name {
          font-size: 13px;
        }

        .p-type {
          font-size: 12px;
          color: #666;
          margin-top: 8px;
        }

        .p-price {
          font-size: 13px;
          color: #f23030;
          margin-top: 8px;
        }

        .p-cart{
          position: relative;
          float: right;
          background-color: #b70101;
          height: 16px;
          width: 40px;
          background-image: url("../../public/img/icons-png/shoppingCar-white.png");
          background-repeat: no-repeat;
          background-position: center;
          background-position-x: 45%;
          background-size: 16px;
          border-radius: 50px;
          margin-right: 26px;
          i{
            position: absolute;
            right: -18px;
            font-size: 12px;
            top: 2px;
          }
        }
      }
    }
  }

  .left-menu {
    position: fixed;
    height: calc(100% - 116px);
    left: -106px;
    width: 125px;
    background-color: #fff;
    top: 76px;
    border-radius: 0 18px 0 0;
    border: 1px solid #d7d7d7;
    overflow: hidden;
    transition: 0.5s;
    margin-bottom: 120px;

    .left-switch {
      width: 20px;
      background-color: #fff;
      position: absolute;
      right: 0;
      height: 100%;

      img {
        position: absolute;
        top: 42%;
        left: 2px;
        width: 20px;
        transform: rotate(90deg);
        transition: 0.5s;
      }
    }

    ul {
      position: absolute;
      height: 100%;
      width: 106px;
      background-color: #f0f0f0;
      overflow: auto;

      li {
        width: 106px;
        height: 50px;
        text-align: center;
        line-height: 50px;
        border-bottom: 1px solid #d7d7d7;
        padding: 0;
        font-size: 12px;
        color: #333;
      }

      li.left-item-select {
        background-color: #fff;
      }
    }
  }

  .left-menu-show {
    left: 0;

    .left-switch {
      img {
        transform: rotate(-90deg);
      }
    }

  }
}

.right-pad {
  position: fixed;
  /* right: -85%; */
  right: -85%;
  top: 0;
  width: 85%;
  height: 100%;
  background-color: #f7f7f7;
  z-index: 103;
  transition: 580ms;
  z-index: 101;

  ul {
    list-style: none;
    overflow: hidden;
  }

  .list-pad {
    overflow: auto;
    height: 100%;

    .f-type-list {
      overflow: hidden;

      > li {
        padding: 10px;
        background-color: #fff;
        margin-bottom: 10px;

        .f-item-list {
          overflow: hidden;
          display: flex;
          flex-wrap: wrap;

          li {
            flex-basis: 33.3%;

            span {
              display: block;
              margin-top: 10px;
              margin-right: 10px;
              background: #eee;
              border: 1px solid #eee;
              padding: 5px 0;
              text-align: center;
              border-radius: 6px;
              font-size: 13px;
              overflow: hidden;
              height: 29px;
              line-height: 22px;
            }

            .prop-select {
              border: 1px solid red;
              background: #fff;
              color: red;
            }
          }

        }

        p {
          font-size: 14px;
        }
      }
    }
  }

  .right-edit {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;

    button {
      float: left;
      height: 40px;
      width: 50%;
      line-height: 40px;
      text-align: center;
      border: 0px none;
    }
  }
}

.cover {
  position: fixed;
  z-index: 11;
  height: 100%;
  width: 100%;
  left: 0;
  top: 0;
  background-color: rgba(51, 51, 51, 0.36);
}
</style>
